package com.usermanage.ServiceImpl;

import com.contract.Bean.ContractBean1;
import com.contract.Common.ContractIOC;
import com.contract.Common.TablePriceToCatalogIOC;
import com.ordercore.Util.ResponseData.ResponseData;
import com.ordercore.Util.Verify.pzDataVerifyUtil;
import com.pinza.Common.SkuIOC;
import com.usermanage.Mapping.UserCenterMapping;
import com.usermanage.Mapping.UserMapping;
import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.SecurityConfig.UserDetail;
import com.usermanage.Service.SecurityService;
import com.usermanage.Service.UserCenterService;
import com.usermanage.Service.UserService;
import com.usermanage.Service.WechatService;
import com.usermanage.beanParam.UserBean;
import com.usermanage.beanParam.UserCenterBean;
import com.usermanage.util.HttpUtil;
import com.usermanage.util.JsonData;
import com.usermanage.util.StaticUtil;
import com.usermanage.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Slf4j
@Service("wechatService")
public class WechatServiceImpl implements WechatService {

    @Resource
    private UserCenterMapping userCenterMapping;

    @Resource
    private UserCenterService userCenterService;

    @Autowired
    private SecurityService securityService;

    @Resource
    private UserService userService;

    @Resource
    private UserMapping userMapping;

    @Override
    public boolean isExistFindByOpenId(String openId) {
        List<Map> list = userCenterMapping.findByOpenId(openId);
        if (list.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public JsonData unBindEos(String openId) {
        List<Map> list = userCenterMapping.findByOpenId(openId);
        if (list.size() > 0) {
            try {
                Optional<UserCenterBean> userCenterBean = userCenterService.findById(Integer.valueOf(String.valueOf(list.get(0).get("user_id"))));
                userCenterBean.get().setUser_wx_id("");
                userCenterMapping.save(userCenterBean.get());
                return JsonData.success();
            } catch (Exception e) {
                log.info("解绑失败错误信息：" + e.toString());
                return JsonData.fail("解绑失败，请稍后重试");
            }
        } else {
            return JsonData.fail("该用户不存在");
        }
    }

    @Override
    public JsonData boundEOS(HttpServletRequest request, String account, String password, String openid) throws Exception {
        JsonData jsonData = userService.login(request, account, password, null, null);
        if (jsonData.isRet()) {
            Map map = userMapping.findUserDetailForPort(account);
            Optional<UserCenterBean> userCenter = userCenterMapping.findById((Integer.valueOf(map.get("id").toString())));
            UserCenterBean userCenterBean = userCenter.get();
            userCenterBean.setUser_id(Integer.valueOf(map.get("id").toString()));
            userCenterBean.setUser_wx_id(openid);
            userCenterMapping.save(userCenterBean);
            Map mapReps = new HashMap();
            mapReps.put("company_id", SpringSecurityUtils.getCurrentUser().getCompany_id());
            mapReps.put("user_name", SpringSecurityUtils.getCurrentUser().getUsername());
            return JsonData.success(map);
        } else {
            return JsonData.fail();
        }
    }

    @Override
    public JsonData login(HttpServletRequest request, String openId) throws Exception {
        List<Map> list = userCenterMapping.findByOpenId(openId);
        if (list.size() > 0) {
            Optional<UserBean> userBean = userService.findById(Integer.valueOf(String.valueOf(list.get(0).get("user_id"))));
            userService.login(request, userBean.get().getUser_email(), userBean.get().getUser_password().replace("{noop}", ""), null, "Wechat");
            Map map = new HashMap();
            map.put("company_id",SpringSecurityUtils.getCurrentUser().getCompany_id());
            map.put("user_name",SpringSecurityUtils.getCurrentUser().getUsername());
            return JsonData.success(map);
        } else {
            return JsonData.fail();
        }
    }

    @Override
    public JsonData tree() throws IOException {
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        if ("1".equals(userDetail.getCompany_id())) {
            String result = HttpUtil.getDemo(StaticUtil.SKUIP + "/pzCfgCataLogController/pzCfgCataLogTree.json");
            if (result == null) {
                return JsonData.fail("获取分类失败");
            }
            Map map = StringUtil.JsonToMap(result);
            return JsonData.success(map.get("data"));
        } else {
            ContractBean1 contractBean1 = new ContractBean1();
            contractBean1.setCompanyB_id(userDetail.getCompany_id());
            ResponseData responseData = ContractIOC.findOne(contractBean1);
            if (responseData.isRet()) {
                ContractBean1 contractBean11 = (ContractBean1) responseData.getData();
                Integer contract_id1 = contractBean11.getId();
                Integer priceSummaryId1 = Integer.valueOf(contractBean11.getTablePrice_id());
                ResponseData responseData1 = TablePriceToCatalogIOC.getCatalogByCompanyId(contract_id1, priceSummaryId1);
                return JsonData.success(responseData1.getData());
            } else {
                return JsonData.fail(responseData.getMsg());
            }
        }
    }

    @Override
    public JsonData spu(String param) throws IOException {
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        if ("1".equals(userDetail.getCompany_id())) {
            String result = HttpUtil.getDemo(StaticUtil.SKUIP + "/spuCatalogRelateConntroller/getAllRelate.json?page=0&limit=0&param=" + param);
            if (result == null) {
                return JsonData.fail("获取SPU失败");
            }
            Map map = StringUtil.JsonToMap(result);
            return JsonData.success(map.get("data"));
        } else {
            ContractBean1 contractBean1 = new ContractBean1();
            contractBean1.setCompanyB_id(userDetail.getCompany_id());
            ResponseData responseData = ContractIOC.findOne(contractBean1);
            if (responseData.isRet()) {
                ContractBean1 contractBean11 = (ContractBean1) responseData.getData();
                Integer contract_id1 = contractBean11.getId();
                Integer priceSummaryId1 = Integer.valueOf(contractBean11.getTablePrice_id());
                ResponseData responseData1 = TablePriceToCatalogIOC.getSpuByCls3(contract_id1, priceSummaryId1, param);
                return JsonData.success(responseData1.getData());
            } else {
                return JsonData.fail(responseData.getMsg());
            }
        }
    }

    @Override
    public JsonData skuList(String page, String limit, String key, String spuCode, String cls) throws IOException {
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        if ("1".equals(userDetail.getCompany_id())) {
            StringBuffer buffer = new StringBuffer();
            buffer.append(StaticUtil.SKUIP + "/sku/getSkuListPageBySpuCode.json?page="+page+"&limit="+limit);
            if(StringUtils.isNotBlank(key)){
            buffer.append("&key="+key);
            }
            if(StringUtils.isNotBlank(spuCode)){
                buffer.append("&spuCode="+spuCode);
            }
            String result = HttpUtil.getDemo(buffer.toString());
            if (result == null) {
                return JsonData.fail("获取SKU列表失败");
            }
            Map map = StringUtil.JsonToMap(result);
            return JsonData.success(map.get("data"));
        } else {
            ContractBean1 contractBean1 = new ContractBean1();
            contractBean1.setCompanyB_id(userDetail.getCompany_id());
            ResponseData responseData = ContractIOC.findOne(contractBean1);
            if (responseData.isRet()) {
                ContractBean1 contractBean11 = (ContractBean1) responseData.getData();
                Integer contract_id1 = contractBean11.getId();
                ResponseData responseData1 = ContractIOC.contractSkuList(Integer.valueOf(page), Integer.valueOf(limit), contract_id1, spuCode, cls, key);
                return JsonData.success(responseData1.getData());
            } else {
                return JsonData.fail(responseData.getMsg());
            }
        }
    }

    @Override
    public JsonData skuInfo(String sku_code) {
      ResponseData responseData = SkuIOC.skuDetail(sku_code);
      return JsonData.success(responseData.getData());
    }

}
